﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using ChatGPT.Net;
using ChatGPT.Net.DTO;
using Microsoft.Extensions.ObjectPool;
using NLog;

namespace ChatGpt_WebApp.ThirdApi;

/// <summary>
/// Pawan 官网逆向 API
/// </summary>
public class PawanReverseApi : ChatApiBase
{
    readonly ChatGptUnofficial bot;

    public PawanReverseApi(ILogger<PawanReverseApi> logger, ApiConfig config) : base(logger, config)
    {
        bot = new ChatGptUnofficial(apiContext.SessionToken, new ChatGptUnofficialOptions()
        {

        });
    }



    /// <summary>
    /// 向AI提问
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="question"></param>
    /// <param name="conversationId"></param>
    /// <returns></returns>
    public override async Task<ChatResult> Ask(string question, string conversationId)
    {
        var result = new ChatResult();

        try
        {
            var count = 1;
            do
            {
                result.Content = await bot!.Ask(question, conversationId);
                //循环等待回答
                if (string.IsNullOrWhiteSpace(result.Content)) await Task.Delay(1000);
            } while (string.IsNullOrWhiteSpace(result.Content) && ++count < 5);

            if (string.IsNullOrWhiteSpace(result.Content))
            {
                logger.LogWarning("回答为空" + question.Length);
                result.Status = ChatResultStatus.TimeOut;
                result.Success = false;
                result.Content = "源服务器问答请求有些繁忙，待会儿再试试吧";
                return result;
            }
        }
        catch (System.Net.Http.HttpRequestException e)
        {
            logger.LogError(e, "请求异常，问题:" + question);
            result.Exception = e;
            result.Success = false;
            if (e.StatusCode == HttpStatusCode.BadRequest)
            {
                result.Content = $"问题被源服务器拒绝回答了,可能是因为问题过长或者是问题中包含了敏感词汇，请在右上角清理会话后再试试吧!\n异常:{e.Message}";
            }
            else if (e.StatusCode == HttpStatusCode.TooManyRequests)
            {
                result.Content = "提问太过频繁了，请稍后再试试吧!";
            }
            else
            {
                result.Content = "源服务器响应出现异常:" + e.Message;
            }
            return result;
        }
        catch (Exception e)
        {
            logger.LogError(e, "提问时出现错误,问题长度" + question.Length);
            result.Exception = e;
            result.Success = false;
            result.Content = "我这边好像出现了一些异常状况";
            return result;
        }

        result.Success = true;
        result.Status = ChatResultStatus.Success;

        return result;
    }

    /// <summary>
    /// 清除会话记录
    /// </summary>
    /// <param name="conversationId"></param>
    /// <returns></returns>
    public override Task ResetConversation(string conversationId)
    {
        bot.RemoveConversation(conversationId);
        return Task.CompletedTask;
    }
}



